/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ua.kpi.transport.servlet.actions.adding;

import java.io.IOException;
import java.util.Collections;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ua.kpi.transport.db.dao.factory.DAOFactory;
import ua.kpi.transport.db.dao.factory.DBEnum;
import ua.kpi.transport.db.dao.interfaces.IRouteDAO;
import ua.kpi.transport.db.dao.interfaces.IRouteToStationDAO;
import ua.kpi.transport.db.dao.interfaces.IStationDAO;
import ua.kpi.transport.db.entities.RouteBean;
import ua.kpi.transport.db.entities.RouteToStationBean;
import ua.kpi.transport.servlet.actions.IAction;
import ua.kpi.transport.servlet.actions.editing.EditRouteAction;
import ua.kpi.transport.util.settings.Pages;

/**
 *
 * @author harker777
 */
public class AddStationToRouteAction implements IAction{

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        Integer routeId = Integer.valueOf(request.getParameter("routeid"));
        Integer maxNumber;
        
        IRouteDAO rd = DAOFactory.getDAOFactory(DBEnum.MYSQL).getRouteDAO();
        RouteBean route = rd.find(routeId);

        IStationDAO sd = DAOFactory.getDAOFactory(DBEnum.MYSQL).getStationDAO();
        
        IRouteToStationDAO rtsd = DAOFactory.getDAOFactory(DBEnum.MYSQL).getRouteToStationDAO();
        maxNumber = Collections.max(rtsd.findByRoute(route), RouteToStationBean.getStationNumComparator()).getStationNum();
        
        RouteToStationBean rtsb = rtsd.create();
        rtsb.setRouteId(route.getId());
        rtsb.setStationNum(maxNumber + 1);
        rtsd.update(rtsb);
        
        request.setAttribute("route", route);
        request.setAttribute("stations", sd.findAll());
        return Pages.getPage(Pages.STATION_TO_ROUTE_PAGE);
    }
    
}
